<template>
  <el-select 
    v-model="selectvalue" 
    :placeholder="placeholder" 
    filterable 
    v-bind="$attrs" 
    collapse-tags 
    class="elwidth"
    @change="changeFn" 
    @clear="clearFn" 
    @focus="focusFn"
    remote 
    :remote-method="searchOptions" 
    style="width: 100%" 
    clearable
    >
    <el-option 
      v-for="item in options" 
      :key="item.id" 
      :label="labelFormat(item)" 
      :value="valueFormat(item)">
    </el-option>
  </el-select>
</template>
  
<script>
import utils from "@/utils";

export default {
  props: {
    value: {
      required: true,
    },
    url: Function,
    payload: {
      type: Object | Array,
      default: () => { },
    },
    defaultOptions: {
      type: Array,
      default: () => [],
    },
    placeholder: String,
    cacheValue: String,
    labelFormat: {
      type: Function,
      default: (item) => {
        return item.name;
      },
    },
    valueFormat: {
      type: Function,
      default: (item) => {
        return item.code;
      },
    },
  },
  data() {
    return {
      selectvalue: this.value,
      options: [],
      query:''
    };
  },
  watch: {
    value(newValue, oldValue) {
      this.selectvalue = newValue;
    },
    defaultOptions(newValue, oldValue) {
      this.options = newValue;
    },
  },
  mounted() {
    this.searchOptions();
  },
  methods: {
    async searchOptions(query) {
      if (!this.defaultOptions) {
        this.options = this.defaultOptions;
      } 
      if (this.url != null) {
        let { returnObj } = await this.url({
          condition:{
            name:query
          },
          pageSize: 1000,
          pageNo: 1,
        });
        this.options = returnObj.list;
      }
    },
    changeFn(val) {
      let row = {};
      this.options.map((item) => {
        if (val == this.valueFormat(item)) {
          row = { ...item };
        }
      });

      // change事件
      this.$emit("change", {
        value: val,
        row,
      });
      // 默认绑定事件
      this.$emit("input", this.selectvalue);
    },
    async clearFn() {
      // 清除事件
      this.selectvalue = null;
      if (!this.defaultOptions) {
        this.options = this.defaultOptions;
      } 
      if (this.url != null) {
        let { returnObj } = await this.url({
          ...this.payload,
          pageSize: 1000,
          pageNo: 1,
        });
        this.options = returnObj.list;
      }
    },
    async focusFn(){
      if (!this.defaultOptions) {
        this.options = this.defaultOptions;
      } 
      if (this.url != null) {
        let { returnObj } = await this.url({
          ...this.payload,
          pageSize: 1000,
          pageNo: 1,
        });
        this.options = returnObj.list;
      }
    }
  },
};
</script>
  
<style lang="scss" scoped></style>
  